package com.xiyu.service.repository.unit.worker;

import com.xiyu.service.model.unit.rank.UnitRankFetcher;
import com.xiyu.service.model.unit.unit.UnitUnitFetcher;
import com.xiyu.service.model.unit.worker.UnitWorker;
import com.xiyu.service.model.unit.worker.UnitWorkerFetcher;
import com.xiyu.service.model.unit.worker.UnitWorkerTable;
import com.xiyu.service.vo.unit.worker.WorkerPageQueryInput;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.sql.ast.tuple.Tuple2;
import org.babyfish.jimmer.Page;

import java.util.List;

public interface UnitWorkerRepository extends JRepository<UnitWorker, Long> {
    UnitWorkerTable unitWorkerTable = UnitWorkerTable.$;

    default Page<UnitWorker> pageQuery(WorkerPageQueryInput inputVO){
        return
            sql().createQuery(unitWorkerTable)
                    .where(unitWorkerTable.name().likeIf(inputVO.getName()))
                    .whereIf(inputVO.getUnitId() != null, unitWorkerTable.unitId().eq(inputVO.getUnitId()))
                    .orderBy(unitWorkerTable.id().desc())
                    .select(unitWorkerTable.fetch(UnitWorkerFetcher.$.allTableFields()
                            .rank(UnitRankFetcher.$.allTableFields())
                            .unit(UnitUnitFetcher.$.allTableFields())))
                    .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

    default List<Tuple2<String, Long>> findGroupType(){
        return sql().createQuery(unitWorkerTable)
                .groupBy(unitWorkerTable.rankId())
                .select(unitWorkerTable.rank().name(), unitWorkerTable.id().count())
                .execute();
    }


}